﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Simple.Core.Models;

namespace Simple.Core.Web.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        readonly IHostEnvironment hostEnvironment;
        /// <summary>
        /// 全局异常过滤器
        /// </summary>
        /// <param name="_hostEnvironment"></param>
        public GlobalExceptionFilter(IHostEnvironment _hostEnvironment)
        {
            this.hostEnvironment = _hostEnvironment;
        }
        /// <summary>
        /// 全局异常触发
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)//如果异常没有处理
            {
                var result = new ApiResult
                {
                    Code = 500,
                    IsSuccess = false,
                    Message = "服务器发生未处理的异常"
                };

                if (hostEnvironment.IsDevelopment())
                {
                    result.Message += "，" + context.Exception.Message + context.Exception.InnerException?.Message;
                }

                LogHelper.Error(context.Exception.Message, context.Exception);

                context.HttpContext.Response.StatusCode = 200;
                context.ExceptionHandled = true;//异常已处理
                context.Result = new JsonResult(result);
            }
        }
    }
}
